package com.itheima.filter;

import ch.qos.logback.core.util.StringUtil;
import com.itheima.constant.MessageConstant;
import com.itheima.exception.TokenParseFail;
import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        if (uri.contains("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty( token)){
            log.info("token为空");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer emId = (Integer) claims.get("id");
            String operateEmpName = (String) claims.get("name");
            String password = (String) claims.get("password");

            CurrentHolder.setCurrentId(emId);
            CurrentHolder.setCurrentName(operateEmpName);
        } catch (Exception e) {
            log.info("token不正确");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new TokenParseFail(MessageConstant.TOKEN_PARSE_FAIL);
        }
        log.info("放行");
        filterChain.doFilter(request,response);
        CurrentHolder.remove();
    }
}
